<template>
  <div class="ChatSettingLog">
    <n-modal v-model:show="showModal">
      <n-card style="max-width: 600px" @close="showModal = false" closable :title="chatSettings![option].label"
        :bordered="false" size="huge" role="dialog" aria-modal="true">
        <CDynamicForm v-model:FormDataBackups="chatSettings![option].backups" ref="CDynamicFormRef"
          v-model:value="chatSettings![option].template">
          <template v-slot:preTemplate="{ data, backups }">
            <n-form-item :label="data.label" :path="data.prop">
              <n-select key="key" @update:value="preTemplateChange($event, backups!)"
                :options="Object.keys(backups!).map(key => ({ label: key, key, value: key }))"
                :placeholder="'请选择' + data.label" :props="data" v-model:value="data.value">
                <template #action>
                  <n-space>
                    <c-input v-model:value="preTemplateName" placeholder="请输入新预设的名称"></c-input>
                    <n-button :disabled="!preTemplateName" @click="addPreTemplate(data)" dashed type='primary'>
                      确认新增
                    </n-button>
                    <n-button @click="deletePreTemplate(data.value, data)" dashed type='error'>
                      删除当前选中预设
                    </n-button>
                  </n-space>
                </template>
              </n-select>
            </n-form-item>
          </template>
        </CDynamicForm>
      </n-card>
    </n-modal>
  </div>
</template>
<script setup lang='ts'>
const showModal = ref(false)
const option = ref<string>('')
const { chatSettings } = storeToRefs(chatSettingStore())
const show = (key: string) => {
  option.value = key
  showModal.value = true
}
const CDynamicFormRef = ref()
const preTemplateName = ref('')
const addPreTemplate = (data: FormTemplate) => {
  data.value = preTemplateName.value
  CDynamicFormRef.value.addBackupForm(preTemplateName.value)
}
const deletePreTemplate = async (key: string, data: FormTemplate) => {
  CDynamicFormRef.value.deleteBackupForm(key)
  await nextTick()
  data.value = null
}
const preTemplateChange = (value: string, backups: Record<string, string>) => {
  chatSettings.value![option.value].template = JSON.parse(backups[value])
}
defineExpose({
  show
})
</script> 
